import React, { useState, useEffect } from 'react';
import './KeyboardControls.css';

const KeyboardControls = ({ isVisible = true, flightState }) => {
  const [activeKeys, setActiveKeys] = useState(new Set());
  const [isCollapsed, setIsCollapsed] = useState(false);

  useEffect(() => {
    const handleKeyDown = (event) => {
      setActiveKeys(prev => new Set([...prev, event.code]));
    };

    const handleKeyUp = (event) => {
      setActiveKeys(prev => {
        const newSet = new Set(prev);
        newSet.delete(event.code);
        return newSet;
      });
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  if (!isVisible) return null;

  const isKeyActive = (keyCode) => activeKeys.has(keyCode);

  return (
    <div className={`keyboard-controls ${isCollapsed ? 'collapsed' : ''}`}>
      <div className="keyboard-header" onClick={() => setIsCollapsed(!isCollapsed)}>
        <h3>⌨️ Keyboard Controls</h3>
        <div className="header-controls">
          <div className={`control-status ${!flightState?.autopilot ? 'enabled' : 'disabled'}`}>
            {!flightState?.autopilot ? '✅ ENABLED' : '🚫 DISABLED'}
          </div>
          <span className={`collapse-arrow ${isCollapsed ? 'collapsed' : ''}`}>▼</span>
        </div>
      </div>

      {!isCollapsed && (
        <div className="keyboard-content">

      {/* Movement Controls */}
      <div className="control-section">
        <h4>Movement</h4>
        <div className="key-grid movement-grid">
          <div className="key-row">
            <div className={`key-button ${isKeyActive('KeyW') || isKeyActive('ArrowUp') ? 'active' : ''}`}>
              <span className="key-label">W / ↑</span>
              <span className="key-action">Forward</span>
            </div>
          </div>

          <div className="key-row">
            <div className={`key-button ${isKeyActive('KeyA') || isKeyActive('ArrowLeft') ? 'active' : ''}`}>
              <span className="key-label">A / ←</span>
              <span className="key-action">Left</span>
            </div>

            <div className={`key-button ${isKeyActive('KeyS') || isKeyActive('ArrowDown') ? 'active' : ''}`}>
              <span className="key-label">S / ↓</span>
              <span className="key-action">Back</span>
            </div>

            <div className={`key-button ${isKeyActive('KeyD') || isKeyActive('ArrowRight') ? 'active' : ''}`}>
              <span className="key-label">D / →</span>
              <span className="key-action">Right</span>
            </div>
          </div>
        </div>
      </div>

      {/* Altitude Controls */}
      <div className="control-section">
        <h4>Altitude</h4>
        <div className="key-grid altitude-grid">
          <div className={`key-button ${isKeyActive('Space') || isKeyActive('KeyR') ? 'active' : ''}`}>
            <span className="key-label">Space / R</span>
            <span className="key-action">Up</span>
          </div>

          <div className={`key-button ${isKeyActive('ShiftLeft') || isKeyActive('ShiftRight') || isKeyActive('KeyF') ? 'active' : ''}`}>
            <span className="key-label">Shift / F</span>
            <span className="key-action">Down</span>
          </div>
        </div>
      </div>

      {/* Rotation Controls */}
      <div className="control-section">
        <h4>Rotation</h4>
        <div className="key-grid rotation-grid">
          <div className={`key-button ${isKeyActive('KeyQ') ? 'active' : ''}`}>
            <span className="key-label">Q</span>
            <span className="key-action">Rotate Left</span>
          </div>

          <div className={`key-button ${isKeyActive('KeyE') ? 'active' : ''}`}>
            <span className="key-label">E</span>
            <span className="key-action">Rotate Right</span>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="control-section">
        <h4>Quick Actions</h4>
        <div className="key-grid actions-grid">
          <div className={`key-button action-key ${isKeyActive('KeyT') ? 'active' : ''} ${flightState?.isFlying ? 'disabled' : ''}`}>
            <span className="key-label">T</span>
            <span className="key-action">Take Off</span>
          </div>

          <div className={`key-button action-key ${isKeyActive('KeyL') ? 'active' : ''} ${!flightState?.isFlying ? 'disabled' : ''}`}>
            <span className="key-label">L</span>
            <span className="key-action">Land</span>
          </div>

          <div className={`key-button emergency-key ${isKeyActive('Escape') ? 'active' : ''}`}>
            <span className="key-label">ESC</span>
            <span className="key-action">Emergency Stop</span>
          </div>
        </div>
      </div>

      {/* Status Information */}
      <div className="control-section">
        <h4>Status</h4>
        <div className="status-info">
          <div className="status-item">
            <span className="status-label">Flight Mode:</span>
            <span className={`status-value ${flightState?.isFlying ? 'flying' : 'grounded'}`}>
              {flightState?.isFlying ? 'FLYING' : 'GROUNDED'}
            </span>
          </div>

          <div className="status-item">
            <span className="status-label">Control:</span>
            <span className={`status-value ${flightState?.autopilot ? 'auto' : 'manual'}`}>
              {flightState?.autopilot ? 'AUTOPILOT' : 'MANUAL'}
            </span>
          </div>

          {flightState?.velocity && (
            <div className="status-item">
              <span className="status-label">Speed:</span>
              <span className="status-value">
                {flightState.velocity.length().toFixed(1)} m/s
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Instructions */}
      <div className="control-section">
        <h4>Tips</h4>
        <div className="instructions">
          <ul>
            <li>Use <strong>Arrow Keys</strong> or <strong>WASD</strong> for movement</li>
            <li>Hold keys for continuous movement</li>
            <li>Press <strong>T</strong> to take off before flying</li>
            <li>Use <strong>ESC</strong> for emergency stop</li>
            <li>Autopilot disables manual controls</li>
          </ul>
        </div>
      </div>
        </div>
      )}
    </div>
  );
};

export default KeyboardControls;
